// SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
// SPDX-License-Identifier: Mulan PSL v2
package com.geniusai.aip.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.geniusai.aip.auth.exception.AuthLoginException;
import com.geniusai.aip.auth.exception.AuthLoginExceptionEnum;
import com.geniusai.aip.feature.common.utils.executor.TaskExecutorContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.HashSet;

import static com.geniusai.aip.auth.constants.AuthCommonConstants.*;

/**
 * @Description
 * @Author: zhangkun91535
 * @Date: 2022-09-29 11:15
 * @Version 1.0
 **/
@Slf4j
@Service
public class RestDataAuthService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${spring.data-auth.url}")
    private String dataAuthUrl;




    /**
     * @Author zhangkun91535
     * @Description 授予管理员权限
     * @Date 2022/9/29 11:17
     **/
    public void grantDataAuthRoleIfAdminAsync(Integer role, String username) {
        log.info("data.auth.role=> role : {}",role);
        TaskExecutorContext.getTaskExecutor().submit(() -> {
            if (role != null && role == 1) {
                //是管理员
                this.grantAdminRole(username);
            }
        });

    }


    public void editDataAuthRoleAsync(Integer role, String username){

        log.info("data.auth.role=> role : {}", role);
        TaskExecutorContext.getTaskExecutor().submit(() -> {
            if (role != null) {
                if (role == 1) {
                    //管理员
                    this.grantAdminRole(username);
                } else if (role == 0) {
                    //撤销管理员
                    this.revokeAdminRole(username);
                }

            }
        });
    }


    /**
     * @Author zhangkun91535
     * @Description 给用户授予admin数据权限
     * @Date 2022/9/29 11:27
     **/
    public void grantAdminRole(String username) {
        log.info("user.data.auth.grant=> grant admin role start :{}", username);

        try {
            //添加请求头
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/json");
//            headers.add("Cookie", cookie);
            //3、组装请求头和参数
            JSONObject request = new JSONObject();
            request.put("resourceName", "-");
            request.put("resourceType", "-");
            HashMap<String, String> map = new HashMap<>();
            map.put(username, "admin");
            request.put("grantUserRoles", map);
            HttpEntity<String> formEntity = new HttpEntity<>(  JSON.toJSONString(request),headers);
            String authUrl = dataAuthUrl + POST_DATA_AUTH_USER_ROLE;
            log.info("user.data.auth.grant=>authUrl [ {} ],body: [ {} ]",authUrl,request);
            //4、发起post请求
            ResponseEntity<String> dataSpaceCapacity
                    = restTemplate.exchange(authUrl, HttpMethod.POST, formEntity, String.class);
            log.info("user.data.auth.grant=>resp: [{}]" , dataSpaceCapacity.getBody());

        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new AuthLoginException(AuthLoginExceptionEnum.CREATE_DATASPACE_ERROR, "授予数据权限admin角色异常: " + e.getMessage());
        }
    }


    /**
     * @Author zhangkun91535
     * @Description 撤销用户授予admin数据权限
     * @Date 2022/9/29 11:27
     **/
    public void revokeAdminRole(String username) {
        log.info("user.data.auth.revoke=> revoke admin role start :{}", username);

        try {
            //添加请求头
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/json");
//            headers.add("Cookie", cookie);
            //3、组装请求头和参数
            JSONObject request = new JSONObject();
            request.put("resourceName", "-");
            request.put("resourceType", "-");
            HashSet<String> set = new HashSet<>();
            set.add(username);
            request.put("revokeUsernames", set);
            HttpEntity<String> formEntity = new HttpEntity<>(  JSON.toJSONString(request),headers);
            String authUrl = dataAuthUrl + POST_DATA_AUTH_USER_ROLE_REVOKE;
            log.info("user.data.auth.revoke=>authUrl [ {} ],body:{}",authUrl,request);
            //4、发起post请求
            ResponseEntity<String> dataSpaceCapacity
                    = restTemplate.exchange(authUrl, HttpMethod.POST, formEntity, String.class);
            log.info("user.data.auth.revoke=>resp: [{}]" , dataSpaceCapacity.getBody());

        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new AuthLoginException(AuthLoginExceptionEnum.CREATE_DATASPACE_ERROR, "撤销数据权限admin角色异常: " + e.getMessage());
        }
    }

    /**
     * @Author zhangkun91535
     * @Description 删除用户所有数据权限
     * @Date 2022/9/29 11:43
     **/
    public void revokeAllDataAuthAsync(String username) {
        log.info("user.data.auth.revokeAll=> revoke admin role start :{}", username);
        TaskExecutorContext.getTaskExecutor().submit(() -> {
            try {
                //添加请求头
                HttpHeaders headers = new HttpHeaders();
                headers.add("Content-Type", "application/json");
//            headers.add("Cookie", cookie);
                //3、组装请求头和参数
                HttpEntity<String> formEntity = new HttpEntity<>(headers);
                String authUrl = dataAuthUrl + DELETE_DATA_AUTH_USER;
                log.info("user.data.auth.revokeAll=>authUrl [ {} ]", authUrl);
                //4、发起post请求
                ResponseEntity<String> dataSpaceCapacity
                        = restTemplate.exchange(authUrl, HttpMethod.DELETE, formEntity, String.class, username);
                log.info("user.data.auth.revokeAll=>resp: [{}]", dataSpaceCapacity.getBody());

            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new AuthLoginException(AuthLoginExceptionEnum.CREATE_DATASPACE_ERROR, "删除用户数据权限异常: " + e.getMessage());
            }
        });

    }
}
